<template>
  <div class="data-dict-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据字典</span>
          <div class="header-description">
            <el-text type="info" size="small">
              展示模板中可以填写的字段信息
            </el-text>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="字段中文名">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入字段中文名进行模糊查询"
              clearable
              style="width: 300px;"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据字典列表 -->
      <div class="table-section">
        <el-table 
          :data="dictList" 
          v-loading="loading"
          style="width: 100%"
          stripe
          :empty-text="loading ? '加载中...' : '暂无数据'"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" show-overflow-tooltip />
          <el-table-column prop="name" label="字段中文名" min-width="200" show-overflow-tooltip />
          <el-table-column prop="field_name" label="字段英文名" min-width="200" show-overflow-tooltip />
          <el-table-column prop="collection" label="所在集合" width="150" show-overflow-tooltip />
          <el-table-column prop="parent_field" label="父级字段" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.parent_field" class="parent-field">
                {{ scope.row.parent_field }}
              </span>
              <span v-else class="no-parent">-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleCopy(scope.row)"
                :icon="CopyDocument"
                circle
                title="复制字段路径"
                class="copy-btn"
              />
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, CopyDocument } from '@element-plus/icons-vue'
import { dataDictApi } from '../api/index.js'

// 响应式数据
const loading = ref(false)
const dictList = ref([])

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})



// 获取数据字典列表
const getDictList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      currentPage: pagination.currentPage,
      size: pagination.pageSize
    }
    
    // 如果有关键词，添加到查询参数中
    if (searchForm.name && searchForm.name.trim()) {
      params.keyword = searchForm.name.trim()
    }
    
    // 调用API
    const response = await dataDictApi.query(params)
    
    // 处理响应数据
    if (response && response.data) {
      const data = response.data
      dictList.value = data.list || data.data || []
      pagination.total = data.total || 0
      
      // 如果返回的数据结构与预期不同，尝试适配
      if (!data.list && !data.data && Array.isArray(data)) {
        dictList.value = data
        pagination.total = data.length
      }
    } else {
      dictList.value = []
      pagination.total = 0
    }
    
  } catch (error) {
    console.error('获取数据字典失败:', error)
    ElMessage.error('获取数据字典失败')
    dictList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getDictList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  pagination.currentPage = 1
  getDictList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getDictList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getDictList()
}

// 复制字段路径
const handleCopy = async (row) => {
  try {
    // 构建字段路径：父级字段.字段英文名
    let fieldPath = ''
    if (row.parent_field && row.parent_field.trim()) {
      fieldPath = `${row.collection}.${row.parent_field}.${row.field_name}`
    } else {
      fieldPath = `${row.collection}.${row.field_name}`
    }
    
    // 用双大括号包围
    const copyText = `{{${fieldPath}}}`
    
    // 使用 Clipboard API 复制到剪贴板
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(copyText)
      ElMessage.success('字段路径已复制到剪贴板')
    } else {
      // 降级方案：使用传统的复制方法
      const textArea = document.createElement('textarea')
      textArea.value = copyText
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        document.execCommand('copy')
        ElMessage.success('字段路径已复制到剪贴板')
      } catch (err) {
        ElMessage.error('复制失败，请手动复制')
        console.error('复制失败:', err)
      } finally {
        document.body.removeChild(textArea)
      }
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请重试')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getDictList()
})
</script>

<style scoped>
.data-dict-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-description {
  margin-left: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-form {
  margin-bottom: 0;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.parent-field {
  color: #409EFF;
  font-family: 'Courier New', monospace;
  background-color: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.no-parent {
  color: #909399;
  font-style: italic;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table .cell) {
  word-break: break-all;
}

:deep(.el-table .el-table__header) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

/* 复制按钮样式 */
.copy-btn {
  transition: all 0.3s ease;
}

.copy-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-button.is-circle) {
  width: 32px;
  height: 32px;
  padding: 0;
}
</style>
